const db = uniCloud.database();
const dbCmd = db.command;
const { defaultChpaters, chapterNameSplitStr } = require('../../config/index.js');
module.exports = async function(options = {}) {
	const token = this.getUniIdToken();
	let { chapters, uid, chapters_nots, chapters_custom_nots } = options;
	if (!token) {
		throw new Error('非法请求');
	}
	const user_chapters = chapters.filter(item => defaultChpaters.find(item2 => item2 === item));
	// 需要添加的自定义课程篇章
	let chapters_custom = chapters.filter(item => !defaultChpaters.find(item2 => item2 === item));
	chapters_custom = chapters_custom.map(item => `my${chapterNameSplitStr}${item}`);
	// 需要删除的自定义课程篇章
	const chapters_custom_remove = chapters_custom_nots.map(item => `my${chapterNameSplitStr}${item}`);
	await Promise.all([
		db.collection('uni-id-users').where({ token }).update({
			chapters: dbCmd.pullAll(chapters_nots),
			chapters_custom: dbCmd.pullAll(chapters_custom_remove)
		}),
		db.collection('uni-id-users').where({ token }).update({
			chapters: dbCmd.addToSet({
				$each: user_chapters
			}),
			chapters_custom: dbCmd.addToSet({
				$each: chapters_custom
			})
		})
	])
	return {
		code: 0,
		msg: '修改成功'
	}
}